package com.ltzuche.web;

import java.sql.SQLException;
import java.util.Date;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.ltzuche.model.Car;
import com.ltzuche.model.CarInfo;

public class CarController extends BaseController {
	
	public void detail() {
		setAttr("car", Car.dao.findById(getPara()));
		setAttr("carInfo", CarInfo.dao.findById(getPara()));
		renderJsp("detail.jsp");
	}
	
	public void input() {
		renderJsp("form.jsp");
	}
	
	public void add() {
		try {
			final Car car = getModel(Car.class);
			final CarInfo carInfo = getModel(CarInfo.class);
			boolean flag = Db.tx(new IAtom() {
				@Override
				public boolean run() throws SQLException {
//					car.set("create_time", new Date());
					carInfo.set("id", car.getStr("id"));
//					carInfo.set("create_time", new Date());
					return car.save()&&carInfo.save();
				}
			});
			renderJson(flag?success("保存成功！！"):fail("保存失败！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("保存失败！！"));
		}
	}
	
	public void list() {
		setAttr("list", Car.dao.find("select * from car"));
		renderJsp("list.jsp");
	}
	
	public void edit() {
		setAttr("car", Car.dao.findById(getPara()));
		setAttr("carInfo", CarInfo.dao.findById(getPara()));
		renderJsp("edit.jsp");
	}
	
	public void update() {
		try {
			final Car car = getModel(Car.class);
			final CarInfo carInfo = getModel(CarInfo.class);
			boolean flag = Db.tx(new IAtom() {
				@Override
				public boolean run() throws SQLException {
					return car.update()&&carInfo.update();
				}
			});
			renderJson(flag?success("保存成功！！"):fail("保存失败！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("保存失败！！"));
		}
	}

}
